package com.org.cys.plugin;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonGenerator;

import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.Module;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.ser.std.ToStringSerializer;

import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * 自定义的JSON转换Mapper
 * 
 * @author caiyushen
 * @date 2017-07-06
 * 
 */
public class CustomObjectMapper extends ObjectMapper {

	public CustomObjectMapper() {
		super();
		// 设置null转换""
		getSerializerProvider().setNullValueSerializer(new NullSerializer());
		// 设置日期转换yyyy-MM-dd HH:mm:ss
		setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		
		// 设置Long类型转换为String
		SimpleModule simpleModule = new SimpleModule("caiyushen", new Version(0, 1, 1, "FINAL"));
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
		super.registerModule(simpleModule);
	}

	// null的JSON序列
	private class NullSerializer extends JsonSerializer<Object> {
		public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
				throws IOException, JsonProcessingException {
				jgen.writeString("");
//				jgen.writeNull();
		}
	}
}